package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Locale;

@Controller
@RequestMapping("/cargo/invoice")
@Slf4j
public class InvoiceController extends BaseController {

    @Reference
    private InvoiceService invoiceService;
    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;
    @Reference
    private ContractService contractService;
    @Reference
    private ShippingService shippingService;

    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行分页的方法");
        // 构造查询对象
        InvoiceExample example = new InvoiceExample();
        example.setOrderByClause("invoice_time desc");
        //分页
        PageInfo<Invoice> pageInfo =
                invoiceService.findByPage(example,pageNum, pageSize);
        // 存储查询结果
        request.setAttribute("pageInfo", pageInfo);

        // 进入厂家管理列表
        return "cargo/invoice/invoice-list";
    }

    /**
     * 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd(String id) {
        //委托金额
        Double freight = 10.0;

        //根据委托单找报运的合同号
        Packing packing = packingService.findById(id);
        //报运的合同号
        String scno = packing.getExportNos();
        //装箱金额
        Double packingMoney = packing.getPackingMoney();
        //发票金额
        Double invoiceMoney = packingMoney+freight;
        //贸易条款
        String ts = "";
        //根据报运单id查找多个购销合同
        String exportIds = packing.getExportIds();
        String[] split =exportIds.split(",");
        for (String s : split) {
            Export export = exportService.findById(s);
            //根据购销合同查找贸易条款
            String contractids = export.getContractIds();
            String[] all =contractids.split(",");
            for (String cid : all) {
                Contract contract = contractService.findById(cid);
                if (contract.getTradeTerms()!=null){
                    if (s.equals(split[split.length-1])&& cid.equals(all[all.length-1])){
                        ts += contract.getTradeTerms();
                    }else {
                        ts += contract.getTradeTerms()+",";
                    }
                }
                invoiceMoney +=contract.getTotalAmount();
            }
        }

        Invoice invoice = new Invoice();
        invoice.setScNo(scno);
        invoice.setInvoiceMoney(invoiceMoney+"");
        invoice.setTradeTerms(ts);
        request.setAttribute("Invoice",invoice);
        httpSession.setAttribute("id",id);
        return "cargo/invoice/invoice-add";
    }
    /**
     * 添加/
     */
    @RequestMapping("/edit")
    public String edit(Invoice invoice){

        // 判断
        if (StringUtils.isEmpty(invoice.getInvoiceId())) {
            log.info("修改发票信息....");
            invoiceService.insertSelective(invoice);
            Shipping shipping = shippingService.findById(invoice.getShippingId());
            shipping.setState(1);
            shippingService.update(shipping);

        } else {
            log.info("修改发票信息....");
            // 厂家名称为不为空，修改
            invoiceService.updateByPrimaryKeySelective(invoice);
        }
        // 添加成功后，重定向到列表（列表重新查询数据再显示）
        return "redirect:/cargo/invoice/list";
    }

    /**
     * 删除
     */
    @RequestMapping("delete")
    public String delete(String id) {
        invoiceService.deleteByPrimaryKey(id);
        return "redirect:/cargo/invoice/list";
    }

    /**
     * 导出发票
     */
    @RequestMapping("/downloadExcel")
    public String downloadExcel(String id) throws IOException {
        Invoice invoice = invoiceService.selectByPrimaryKey(id);
        Shipping shipping = shippingService.findById(invoice.getShippingId());
        Packing packing = packingService.findById(invoice.getShippingId());
        //【获取excel模板,文件流】
        InputStream in = request.getSession().getServletContext()
                .getResourceAsStream("/make/xlsprint/invoice.xlsx");

        // 第一：导出第一行
        Workbook workbook = new XSSFWorkbook(in);
        // 【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);
        //  //【获取第11行、第11行的第二列】
        Row row = sheet.getRow(11);
        Cell cell = row.getCell(0);
        String title = invoice.getInvoiceId();
        cell.setCellValue(title);
        Cell cell1 = row.getCell(2);
        cell1.setCellValue(new SimpleDateFormat("MMMM-dd-yyyy", Locale.ENGLISH).format(invoice.getInvoiceTime()));
        //cell1.setCellValue(invoice.getInvoiceTime().toString());
        Cell cell2 = row.getCell(5);
        cell2.setCellValue(invoice.getScNo());

        Row row2 = sheet.getRow(13);
        cell = row2.getCell(5);
        cell.setCellValue(shipping.getPortOfLoading());
        cell = row2.getCell(7);
        cell.setCellValue(shipping.getPortOfDischar());

        Row row1 = sheet.getRow(15);
        cell =row1.getCell(0);
        cell.setCellValue(packing.getMarks());
        cell =row1.getCell(2);
        cell.setCellValue(packing.getDescriptions());
        cell = row1.getCell(9);
        cell.setCellValue(invoice.getInvoiceMoney());

        //导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头
        response.setHeader("content-disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
        return "redirect:/cargo/invoice/list";
}
}
